package top.waikin.aspect.repo;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.stereotype.Repository;
import top.waikin.aspect.bean.Demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author WaiKin
 * @date 2022/11/29
 */
@Repository
public class DemoRepo {
  private static final AtomicLong CURRENT_ID = new AtomicLong(0);
  private static final Map<Long, Demo> DEMO_MAP = new HashMap<>();

  static {
    for (int i = 0; i < 5; i++) {
      long id = CURRENT_ID.incrementAndGet();
      Demo demo = new Demo();
      demo.setId(id);
      DEMO_MAP.put(id, demo);
    }
  }

  public Long create(Demo demo) {
    demo.setId(CURRENT_ID.incrementAndGet());
    DEMO_MAP.put(demo.getId(), demo);
    return demo.getId();
  }

  public void delete(Long id) {
    DEMO_MAP.remove(id);
  }

  public void update(Demo demo) {
    if (ObjectUtil.isNotNull(DEMO_MAP.get(demo.getId()))) {
      DEMO_MAP.put(demo.getId(), demo);
    }
  }

  public Demo getById(Long id) {
    return DEMO_MAP.get(id);
  }
}
